package com.xpresso.utils.sockets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.xpresso.utils.exceptions.XpressoException;

public class XSocket {

	private static final Logger log = Logger.getLogger(XSocket.class);
	
	protected ServerSocket serverSocket;
	protected Socket clientSocket;
	protected PrintWriter serverOut;
	
	public XSocket(){
		
	}
	
	public void startSocket(ISocketHandler socketHandler) throws XpressoException{
		log.info("Creating frame internal socket");	
		try {
            serverSocket = new ServerSocket(socketHandler.getPortNumber());
        } catch (IOException e) {
            log.fatal("PANIC: Could not listen on port: " + socketHandler.getPortNumber() + " " + e);
            throw new XpressoException("PANIC: Could not listen on port: " + socketHandler.getPortNumber(), e);
        }

        try {
	        log.info("Socket started. Listening for connections and data");
	        socketHandler.handleSocketReady();
        	clientSocket = serverSocket.accept();
        } catch (IOException e) {
            log.fatal("PANIC: Socket accept failed" + e);
            throw new XpressoException("PANIC: Socket accept failed", e);
        }

        try {
			serverOut = new PrintWriter(clientSocket.getOutputStream(), true);
	        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
	        
	        String incoming;
	        while ((incoming = in.readLine()) != null) {
	        	String result = socketHandler.handleData(incoming, this);
	             if (result != null && result == "Quit")
	                break;
	        }
	        serverOut.close();
	        in.close();
	        clientSocket.close();
	        serverSocket.close();
	        
	        
        } catch (IOException e) {
            log.error("PANIC: Error getting or sending data " + e);
            throw new XpressoException("PANIC: Error getting or sending data " + e, e);			
		}
        
	}
	
	public void sendData(String data) throws XpressoException{
		log.info("Sending data to client: " + data);
		serverOut.println(data);
	}
	
}
